package cn.edu.swufe.surverpark.struts2.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.edu.swufe.surverpark.datasourcerouter.SurveyparkToken;
import cn.edu.swufe.surverpark.model.Answer;
import cn.edu.swufe.surverpark.model.Page;
import cn.edu.swufe.surverpark.model.Survey;
import cn.edu.swufe.surverpark.struts2.service.SurveyService;
import cn.edu.swufe.surverpark.util.StringUtil;
import cn.edu.swufe.surverpark.util.ValidateUtil;

/**
 * @author 陈龙 E-mail:529914446@qq.com
 * @version创建时间:2015年5月1日下午8:19:05 参与调查
 */
@Controller
@Scope("prototype")
public class EngageSurveyAction extends BaseAction<Survey> implements
		ServletContextAware, SessionAware, ParameterAware {

	/**
	 * 
	 */
	@Resource
	private SurveyService surveyService;

	private List<Survey> surveys;

	private static final String CURRENT_SURVEY = "current_survey";
	private static final String ALL_PARAMS_MAP = "all_params_map";

	private static final long serialVersionUID = 745396699281340052L;

	public String findAllAvailableSurveys() {
		this.surveys = surveyService.findAllAvailableSurveys();
		return "engageSurveyListPage";
	}

	public String getImageUrl(String path) {
		if (ValidateUtil.isValid(path)) {
			String absPath = sc.getRealPath(path);
			File f = new File(absPath);
			if (f.exists()) {
				return sc.getContextPath() + path;
			}
		}
		return sc.getContextPath() + "/question.bmp";
	}

	public List<Survey> getSurveys() {
		return surveys;
	}

	public void setSurveys(List<Survey> surveys) {
		this.surveys = surveys;
	}

	private ServletContext sc;

	@Override
	public void setServletContext(ServletContext arg0) {
		this.sc = arg0;

	}

	private Integer sid;
	private Page currPage;

	public String entry() {
		this.currPage = surveyService.getFirstPage(sid);
		session.put(CURRENT_SURVEY, currPage.getSurvey());
		session.put(ALL_PARAMS_MAP, new HashMap<Integer, Map<String, String>>());
		return "engageSurveyPage";
	}

	public Integer getSid() {
		return sid;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public Page getCurrPage() {
		return currPage;
	}

	public void setCurrPage(Page currPage) {
		this.currPage = currPage;
	}

	private Map<String, Object> session;

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;

	}

	private Integer currPid;

	public String doEngageSurvey() {
		String submitName = getSubmitName();
		if (submitName.endsWith("pre")) {
			// 上一步
			mergeParamsIntoSession();
			this.currPage = surveyService.getPrePage(currPid);
			return "engageSurveyPage";
		} else if (submitName.endsWith("next")) {
			// 下一步
			mergeParamsIntoSession();
			this.currPage = surveyService.getNextPage(currPid);
			return "engageSurveyPage";
		} else if (submitName.endsWith("done")) {
			// 完成
			mergeParamsIntoSession();
			SurveyparkToken token = new SurveyparkToken();
			token.setSurvey(getCurrentSurvey());
			SurveyparkToken.bindToken(token);
			
			surveyService.saveAnswers(processAnswers());
			clearSessionData();
			return "engageSureyAction";

		} else if (submitName.endsWith("exit")) {
			// 退出
			clearSessionData();
			return "engageSureyAction";

		}
		return null;
	}

	private List<Answer> processAnswers() {
		Map<Integer,String> matrixRadioMap = new HashMap<Integer,String>();
		List<Answer> answers = new ArrayList<Answer>();
		Answer a = null;
		String key = null;
		String[] value = null;
		Map<Integer,Map<String,String[]>>allMap = getAllParamsMap();
		for(Map<String,String[]> map:allMap.values()){
			for(Entry<String,String[]>entry:map.entrySet()){
				key = entry.getKey();
				value = entry.getValue();
				if(key.startsWith("q")){
					//常规参数
					if(!key.contains("other")&&!key.contains("_")){
						a = new Answer();
						a.setAnswerIds(StringUtil.arr2Str(value));
						a.setQuestionId(getQid(key));
						a.setSurveyId(getCurrentSurvey().getId());
						a.setOtherAnswer(StringUtil.arr2Str(map.get(key + "other")));
						answers.add(a);
					}
					else if(key.contains("_")){
						Integer radioQid = getMatrixRadioQid(key);
						String oldValue = matrixRadioMap.get(radioQid);
						if(oldValue == null)
							matrixRadioMap.put(radioQid,StringUtil.arr2Str(value));
						else
							matrixRadioMap.put(radioQid,oldValue + "," + StringUtil.arr2Str(value));
					}
				}
				
			}
		}
		//单独处理矩阵式单选按钮
		processMatrixRadioMap(matrixRadioMap,answers);
		return answers;
	}

	private void processMatrixRadioMap(Map<Integer, String> map,
			List<Answer> answers) {
		Answer a = null;
		Integer key = null;
		String value = null;
		for(Entry<Integer,String> entry:map.entrySet()){
			key = entry.getKey();
			value = entry.getValue();
			a = new Answer();
			a.setAnswerIds(value);
			a.setQuestionId(key);
			a.setSurveyId(getCurrentSurvey().getId());
			answers.add(a);
		}
		
	}

	private Integer getMatrixRadioQid(String key) {
		return Integer.parseInt(key.substring(1,key.lastIndexOf("_")));
	}

	private Survey getCurrentSurvey() {
		return (Survey) session.get(CURRENT_SURVEY);
	}

	private Integer getQid(String key) {
		// TODO Auto-generated method stub
		return Integer.parseInt(key.substring(1));
	}

	private void clearSessionData() {
		session.remove(CURRENT_SURVEY);
		session.remove(ALL_PARAMS_MAP);

	}

	private void mergeParamsIntoSession() {
		Map<Integer, Map<String, String[]>> allParamsMap = getAllParamsMap();
		allParamsMap.put(currPid, paramsMap);
	}

	@SuppressWarnings("unchecked")
	private Map<Integer, Map<String, String[]>> getAllParamsMap() {
		return (Map<Integer, Map<String, String[]>>) session
				.get(ALL_PARAMS_MAP);
	}

	private String getSubmitName() {
		for (String key : paramsMap.keySet())
			if (key.startsWith("submit_"))
				return key;
		return null;
	}

	private Map<String, String[]> paramsMap;

	@Override
	public void setParameters(Map<String, String[]> arg0) {
		// TODO Auto-generated method stub
		this.paramsMap = arg0;
	}

	public Integer getCurrPid() {
		return currPid;
	}

	public void setCurrPid(Integer currPid) {
		this.currPid = currPid;
	}

	public String setTag(String name, String value, String selTag) {
		Map<String, String[]> map = getAllParamsMap().get(currPage.getId());
		String[] values = map.get(name);
		if (StringUtil.contains(values, value)) {
			return selTag;
		}
		return "";
	}

	public String setText(String name) {
		Map<String, String[]> map = getAllParamsMap().get(currPage.getId());
		String[] values = map.get(name);
		return "value='" + values[0] + "'";
	}

}
